<?php

class ProductCustomFilter extends BaseProductFormFilter{
    
  public function configure(){
	$this->useFields(array('price', 'brand_name'));
	
	$this->widgetSchema['price'] = new sfWidgetFormSelect(array('choices' =>
		$this->getPriceRanges() ), array() );
  	$this->validatorSchema['price'] = new sfValidatorPass(array('required' => false));

	$this->widgetSchema['brand_name'] = new sfWidgetFormSelect(array('choices' =>
		$this->getBrandNamesChoices() ), array() );
  	$this->validatorSchema['brand_name'] = new sfValidatorPass(array('required' => false));

	$this->widgetSchema['product_group'] = new sfWidgetFormSelect(array('choices' =>
		$this->getProductGroupChoices() ), array( 'size' => 3 ) );
	$this->validatorSchema['product_group'] = new sfValidatorPass(array('required' => false));

	$this->widgetSchema['sort'] = new sfWidgetFormSelect(array('choices' =>
		$this->getSortChoices() ), array( 'size' => 3 ) );
	$this->validatorSchema['sort'] = new sfValidatorPass(array('required' => false));
  }


  public function getProductGroupChoices(){

  	$result = array();


  	foreach( Doctrine::getTable('ProductGroup')->findAll()  as $pg ){
  		if( $pg['title'] != 'root' )
  		$result[$pg['id']] = $pg['title'];
  	}

  	return $result;


  }
  
    protected function addPriceColumnQuery(Doctrine_Query $query, $field, $value) {
		list($low, $high) = explode('-', $value);

		if(preg_match('/(\d+)-(\d+)/i', $value)){
			$query->andWhere( 'r.price >= ?', $low )
			->andWhere('r.price <=  ?', $high);
		}
    }

    protected function addProductGroupColumnQuery(Doctrine_Query $query, $field, $values) {


    }
    

    protected function addBrandNameColumnQuery(Doctrine_Query $query, $field, $value) {
		if($value){

			$query->andWhere( 'r.brand_name = ?', $value );
		}

    }

    
    protected function addSortColumnQuery(Doctrine_Query $query, $field, $value) {
		if($value){
			switch($value){
			case 'A-Z':
				$query->orderBy( 'r.Translation.name asc');
				break;
			case 'Z-A':
				$query->orderBy( 'r.Translation.name desc');
				break;
			default:
				$query->orderBy( 'r.Translation.name');
				break;
			}
		}
    }


    protected function parseFilterExpression($text){
	    preg_match('/([><])? *(\d+)/i',$text, $results);
	    $operator = isset($results[1]) && in_array($results[1], array('>','<')) ? $results[1] : '=';

	    return array('operator' => $operator, 'value' => $results[2]);
    }


    public function getPriceRanges(){
		return array(
			'0-100' => '0-100',
			'101-500' => '101-500',
			'501-1000' => '501-1000'
		);
    }

    public function getBrandNamesChoices(){
		$brands =  Doctrine::getTable('Product')->createQuery('blah')
			   ->select('DISTINCT p.brand_name')
			   ->from('Product p')
			   ->setHydrationMode(Doctrine::HYDRATE_SINGLE_SCALAR)
				->execute();

		return array_combine($brands, $brands);

    }

    public function getSortChoices(){
		return array(
		  'A-Z' => 'A-Z',
		  'Z-A' => 'Z-A'
		);
    }



}